﻿using System;
using System.Xml.Linq;

namespace Microsoft.Services.Clab.UI.Mvvmc.VisualStudio.CustomTools
{
    public static class ExtensionMethods
    {
        public static string GetAttributeValue(this XElement xElement, XName name)
        {
            return GetAttributeValue<string>(xElement, name, string.Empty);
        }

        public static T GetAttributeValue<T>(this XElement xElement, XName name)
        {
            return GetAttributeValue<T>(xElement, name, default(T));
        }

        public static T GetAttributeValue<T>(this XElement xElement, XName name, T defaultValue)
        {
            var xAttr = xElement.Attribute(name);
            if (xAttr != null)
            {
                try
                {
                    return (T)Convert.ChangeType(xAttr.Value, typeof(T));
                }
                catch (Exception)
                {
                    return defaultValue;
                }
            }
            else
            {
                return defaultValue;
            }
        }
    }
}
